package com.example.librarymanagementsystem2;

import com.example.librarymanagementsystem2.entity.Book;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.regex.Pattern;

@Controller
@SessionAttributes("books")
public class libraryControllor {
    @RequestMapping("/")
    public String log() {
        return "log";
    }

    @RequestMapping("/login")
    public String testLog(Model model, @RequestParam String name, @RequestParam String password,
                          @SessionAttribute(required = false) List<Book> books, HttpSession session) {
        if (name.equals("dcx") && password.equals("123")) {
            if (books == null) {
                books = new ArrayList<>();
            }
            model.addAttribute("books", books);
            session.setAttribute("login_state", "yes");
            System.out.println("YES");
            return "bookList";
        }
        return "log";
    }

    @GetMapping("/bookList")
    public String bookList(Model model, @SessionAttribute(required = false) List<Book> books) {
        model.addAttribute("books", books);
        return "bookList";
    }

    @GetMapping("/recordBook")
    public String recordBook() {
        return "recordBook";
    }
    public static boolean isInteger(String str) {
        Pattern pattern = Pattern.compile("^[-\\+]?[\\d]*$");
        return pattern.matcher(str).matches();
    }
    public static boolean judgeIsValid(Book newbook,String filename)
    {
        if(filename.equals("")||newbook.getAuthor().equals("")||newbook.getBookname().equals("")||newbook.getPress().equals("")||newbook.getIntro().equals("")||newbook.getPublicationdate().equals("")||newbook.getStock().equals(""))
        {
            return false;
        }
        if(isInteger(newbook.getStock())==false)
        {
            return false;
        }
        int stockNum=Integer.parseInt(newbook.getStock());
        SimpleDateFormat sdf =   new SimpleDateFormat( "yyyy-MM-dd" );

        Date date = null;
        try {
            date = sdf.parse(newbook.getPublicationdate());
            System.out.println(date);
            Date now=new Date();
            System.out.println(now);
            if(now.before(date))
                return false;
        } catch (ParseException e) {
            e.printStackTrace();
            return false;
        }


        if(stockNum<0)
        {
            return false;
        }
        return true;
    }
    @PostMapping("/addbook")
    public String addBook(Model model,
                          @RequestParam MultipartFile file,
                          @SessionAttribute(required = false) List<Book> books,
                          @ModelAttribute Book newbook
    ) {
        if (books == null) {
            books = new ArrayList<>();
        }
        String filename = file.getOriginalFilename();
        if(!judgeIsValid(newbook,filename))
            return "recordBook";
        newbook.setId(books.size());
        filename = newbook.getId() + filename;
        newbook.setFilename(filename);//保存上传的文件
        String parentDir = "D:\\study\\Web开发技术\\library-management-system2\\src\\main\\resources\\static\\images";
        File parent = new File(parentDir);
        File dest = new File(parent, filename);
        try {
            file.transferTo(dest);
        } catch (IOException e) {
            e.printStackTrace();
        }
        books.add(newbook);
        return "success";
    }

    @GetMapping("/delete")
    public String delete(Model model, @RequestParam long id, @SessionAttribute(required = false) List<Book> books) {
        //删除原来的封面
        Book book = books.get((int) id);
        String parentDir = "D:\\study\\Web开发技术\\library-management-system2\\src\\main\\resources\\static\\images\\";
        String oldPath = parentDir + book.getFilename();

        File dest = new File(oldPath);
        if (dest.exists()) {
            dest.delete();
        }

        books.remove((int) id);
        return "success";
    }

    @GetMapping("/edit")
    public String edit(Model model, @RequestParam long id, @SessionAttribute(required = false) List<Book> books) {
        Book book = books.get((int) id);
        model.addAttribute("oldbook", book);
        return "edit";
    }

    @PostMapping("/edit")
    public String update(Model model, @ModelAttribute Book book, @RequestParam long id,
                         @RequestParam MultipartFile file, @SessionAttribute(required = false) List<Book> books) {
        if(!judgeIsValid(book,file.getOriginalFilename()))
            return "error";
        if (!file.isEmpty()) {
            Book oldbook = books.get((int) id);
            String parentDir = "D:\\study\\Web开发技术\\library-management-system2\\src\\main\\resources\\static\\images\\";
            String oldPath = parentDir + oldbook.getFilename();
            System.out.println("oldpath" + oldPath);
            File dest = new File(oldPath);
            if (dest.exists()) {
                dest.delete();
            }
            String filename = file.getOriginalFilename();
            filename = book.getId() + filename;
            book.setFilename(filename);
            System.out.println(filename);
            //保存上传的文件
            parentDir = "D:\\study\\Web开发技术\\library-management-system2\\src\\main\\resources\\static\\images";
            File parent = new File(parentDir);
            dest = new File(parent, filename);
            try {
                file.transferTo(dest);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        books.get((int) id).replaceByEntity(book);//没有自动更新，自己写一个

        return "success";
    }
}
